<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
      class="form-search"
    >
      <el-form-item label="物料分类编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入物料分类编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料分类名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入物料分类名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:dict:add']"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          :loading="syncLoading"
          type="warning"
          plain
          icon="Refresh"
          @click="handleSync"
          v-hasPermi="['base:matType:sync']"
          >同步ERP数据</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tableData"
      row-key="id"
      ref="tableUi"
      border
      show-overflow-tooltip
      updateKeyChildren="id"
      max-height="600px"
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="物料分类名称" class-name="leftClassCell" prop="name"> </el-table-column>
      <el-table-column label="物料分类编号" prop="code">
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">{{
            scope.row.code
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="来源" prop="source"> </el-table-column>

      <!--      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="修改时间" align="center" prop="updateTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>-->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Plus"
            @click="handleAdd(scope.row)"
            >新增</el-button
          >
          <el-button
            v-if="scope.row.source !== 'ERP'"
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.source !== 'ERP'"
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      width="700px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item v-if="!disabledForm && form.parentCode" label="上级分类">
          <div>{{ form.parentName }}</div>
        </el-form-item>
        <el-form-item label="物料分类编号" prop="code">
          <el-input
            v-if="!form.id"
            v-model="form.code"
            placeholder="请输入物料分类编号"
          >
            <template v-if="form.parentCode" #prepend>{{
              form.parentCode
            }}</template>
          </el-input>

          <div v-else>{{ form.code }}</div>
        </el-form-item>
        <el-form-item label="物料分类名称" prop="name">
          <el-input
            v-if="!disabledForm"
            v-model="form.name"
            placeholder="请输入物料分类名称"
          />
          <div v-else>{{ form.name }}</div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-if="!disabledForm"
            v-model="form.remark"
            type="textarea"
            :maxlength="200"
            show-word-limit
            placeholder="请输入内容"
          ></el-input>
          <div v-else>{{ form.remark }}</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!disabledForm" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button v-if="!disabledForm" @click="cancel">取 消</el-button>
          <el-button v-if="disabledForm" @click="cancel">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dict">
import {
  queryMatTypeInfoList,
  getMatTypeData,
  deleteMatTypeInfo,
  addMatTypeInfo,
  updateMatTypeInfo,
  syncErpMaterial,
} from "@/api/base/material/MatTypeApi";
import { nextTick } from "vue";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const tableData = ref([]);
const tableUi = ref("tableUi");
const allData = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const syncLoading = ref(false);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const disabledForm = ref(false);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    level: 1,
    name: undefined,
  },
  rules: {
    code: [{ required: true, message: "请输入物料分类编号!", trigger: "blur" }],
    /*status: [
      { required: true, message: "请输入物料分类状态!", trigger: "blur" },
    ],*/
    name: [{ required: true, message: "请输入物料分类名称!", trigger: "blur" }],
    remark: [
      {
        pattern: /^.{0,200}$/,
        message: "备注字数不能超过200字!",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

function load(row, treeNode, resolve) {
  let level = row.level;
  if (!row.level) {
    level = 1;
  }
  treeNode.children = [];
  row.children = [];
  queryMatTypeInfoList({
    level: level + 1,
    code: row.code,
    pageNum: 1,
    pageSize: 10000,
  })
    .then((response) => {
      const subData = [];
      response.rows.forEach((el) => {
        if (el.code.includes(row.code)) {
          el.children = [];
          el.parentName = row.name;
          el.parentCode = row.code;
          el.hasChildren = el.childrenCount>0;
          subData.push(el);
        }
      });
      row.children = subData;

      console.log(tableData.value);
      if (subData.length) {
        resolve(subData);
      } else {
        tableUi.value.store.states.lazyTreeNodeMap.value[row.id] = [];
        resolve([]);
      }
    })
    .catch(() => {
      resolve([]);
    });
}

function resetLazyTree() {
  // $refs.table 在<el-table ref="table">中定义
  tableUi.value.store.states.lazyTreeNodeMap = {};
}

/** 查询物料分类列表 */
function getList() {
  loading.value = true;
  tableData.value = [];
  if (queryParams.value.code || queryParams.value.name) {
    queryParams.value.level = undefined;
  } else {
    queryParams.value.level = 1;
  }
  queryMatTypeInfoList(queryParams.value).then((response) => {
    response.rows.forEach((el) => {
      el.children = [];
      el.hasChildren = el.childrenCount>0;
    });

    tableData.value = response.rows;
    total.value = response.total;
    loading.value = false;
    tableUi.value.$forceUpdate();
  });
}

function handleSync() {
  syncLoading.value = true;
  syncErpMaterial()
    .then((res) => {
      proxy.$modal.msgSuccess("同步成功");

      syncLoading.value = false;
      getList();
    })
    .catch(() => {
      syncLoading.value = false;
    });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    name: undefined,
    remark: undefined,
  };
  proxy.resetForm("formRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  console.log(row);

  form.value.parentCode = row.code;
  form.value.parentName = row.name;
  form.value.level = row.level + 1;
  disabledForm.value = false;
  open.value = true;
  title.value = "新增物料分类";
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleDetail(row) {
  disabledForm.value = true;
  reset();
  const id = row.id;
  getMatTypeData(id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "查看物料分类信息";
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const typeId = row.id || ids.value;
  disabledForm.value = false;
  getMatTypeData(typeId).then((response) => {
    form.value = response.data;
    form.value.parentCode = row.parentCode;
    form.value.parentName = row.parentName;
    open.value = true;
    title.value = "编辑物料分类";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateMatTypeInfo(form.value).then((response) => {
          proxy.$modal.msgSuccess("编辑成功");
          open.value = false;
          getList();
        });
      } else {
        const params = form.value;
        if (params.parentCode) {
          params.code = params.parentCode + params.code;
        }
        addMatTypeInfo(params).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idList = row.id || ids.value.join(",");
  const codes =
    row.code ||
    ids.value
      .map((id) => tableData.value.find((item) => item.id === id)?.code)
      .join(", ");
  proxy.$modal
    .confirm('是否确认删除编号为"' + codes + '"的数据项？')
    .then(function () {
      return deleteMatTypeInfo({ ids: idList });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>
